package com.sat.client.fragment

import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.OnBackPressedCallback
import androidx.fragment.app.Fragment
import com.sat.client.R
import org.salient.artplayer.MediaPlayerManager
import org.salient.artplayer.player.SystemMediaPlayer
import org.salient.artplayer.ui.FullscreenVideoView
import org.salient.artplayer.ui.VideoView

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
const val ARG_URL = "url"


/**
 * A simple [Fragment] subclass.
 * Use the [VideoFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class VideoFragment : Fragment() {
    // TODO: Rename and change types of parameters
    private var url: String? = null
    private var videoView: VideoView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            url = it.getString(ARG_URL)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        val rootView = inflater.inflate(R.layout.fragment_video, container, false)
        videoView = rootView.findViewById(R.id.video_view)
        videoView?.run {
            mediaPlayer = SystemMediaPlayer().apply {
                setDataSource(context, Uri.parse(url))
            }
            prepare()
        }
        return rootView
    }

    companion object {
        /**
         * Use this factory method to create a new instance of
         * this fragment using the provided parameters.
         *
         * @param param1 Parameter 1.
         * @param param2 Parameter 2.
         * @return A new instance of fragment VideoFragment.
         */
        // TODO: Rename and change types and number of parameters
        @JvmStatic
        fun newInstance(param1: String, param2: String) =
            VideoFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_URL, param1)

                }
            }
    }

    override fun onStart() {
        super.onStart()
        // 自定义返回按钮行为
        val callback = object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                if (MediaPlayerManager.blockBackPress(requireActivity())) {
                   return
                }
                requireActivity().supportFragmentManager.popBackStack()
            }
        }
        requireActivity().onBackPressedDispatcher.addCallback(
            viewLifecycleOwner,
            callback
        )
    }
}